<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    width="600px"
    @update:model-value="$emit('update:visible', $event)"
    @close="handleClose"
    class="user-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <!-- 自定义头部 -->
    <template #header>
      <div class="dialog-header">
        <div class="header-icon">
          <el-icon size="24">
            <User />
          </el-icon>
        </div>
        <div class="header-content">
          <h3 class="header-title">{{ title }}</h3>
          <p class="header-subtitle">{{ formData.id ? '编辑用户信息' : '创建新用户账户' }}</p>
        </div>
      </div>
    </template>

    <div class="dialog-body">
      <el-form
        ref="formRef"
        :model="localFormData"
        :rules="rules"
        label-width="90px"
        label-position="left"
        class="user-form"
      >
        <div class="form-section">
          <div class="section-title">
            <el-icon><UserFilled /></el-icon>
            <span>基本信息</span>
          </div>

          <div class="form-grid">
            <el-form-item label="用户名" prop="username" class="form-item-enhanced form-single">
              <el-input
                v-model="localFormData.username"
                placeholder="请输入用户名"
                :disabled="!!formData.id"
                :prefix-icon="User"
                clearable
              />
            </el-form-item>
              <el-form-item v-if="!formData.id" label="密码" prop="password" class="form-item-enhanced form-single">
            <el-input
              v-model="localFormData.password"
              placeholder="请输入密码（6-20位字符）"
              type="password"
              show-password
              :prefix-icon="Lock"
              clearable
            />
          </el-form-item>

          <!--   <el-form-item label="昵称" prop="nickname" class="form-item-enhanced">
              <el-input
                v-model="localFormData.nickname"
                placeholder="请输入昵称"
                :prefix-icon="Avatar"
                clearable
              />
            </el-form-item> -->

            <el-form-item label="邮箱" prop="email" class="form-item-enhanced form-single">
              <el-input
                v-model="localFormData.email"
                placeholder="请输入邮箱地址"
                type="email"
                :prefix-icon="Message"
                clearable
              />
            </el-form-item>

            <el-form-item label="所属部门" prop="departmentId" class="form-item-enhanced form-single">
              <el-tree-select
                v-model="localFormData.departmentId"
                :data="departmentOptions"
                :props="treeProps"
                placeholder="请选择所属部门"
                clearable
                check-strictly
                :render-after-expand="false"
                style="width: 100%"
              />
            </el-form-item>
          </div>
        </div>

        <div class="form-section">
          <div class="section-title">
            <el-icon><Setting /></el-icon>
            <span>权限设置</span>
          </div>

          <div class="form-grid">
            <el-form-item label="角色" prop="role" class="form-item-enhanced">
              <el-select
                v-model="localFormData.role"
                placeholder="请选择角色"
                style="width: 100%"
                :prefix-icon="Setting"
              >
                <el-option label="管理员" value="admin">
                  <div class="role-option">
                    <el-tag type="danger" size="small">管理员</el-tag>
                    <span class="role-desc">拥有所有权限</span>
                  </div>
                </el-option>
                <el-option label="后台人员" value="staff">
                  <div class="role-option">
                    <el-tag type="warning" size="small">后台人员</el-tag>
                    <span class="role-desc">管理系统内容</span>
                  </div>
                </el-option>
                <el-option label="普通用户" value="user">
                  <div class="role-option">
                    <el-tag type="info" size="small">普通用户</el-tag>
                    <span class="role-desc">基础使用权限</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="status" class="form-item-enhanced">
              <div class="status-switch-container">
                <el-switch
                  v-model="statusSwitchValue"
                  size="large"
                  active-text="启用"
                  inactive-text="禁用"
                  active-color="#667eea"
                  inactive-color="#ef4444"
                  @change="handleStatusChange"
                />
              </div>
            </el-form-item>
          </div>
        </div>

       <!--  <div v-if="!formData.id" class="form-section">
          <div class="section-title">
            <el-icon><Lock /></el-icon>
            <span>安全设置</span>
          </div>

          <el-form-item label="密码" prop="password" class="form-item-enhanced form-single">
            <el-input
              v-model="localFormData.password"
              placeholder="请输入密码（6-20位字符）"
              type="password"
              show-password
              :prefix-icon="Lock"
              clearable
            />
          </el-form-item>
        </div> -->
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel" class="cancel-btn" size="large">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" class="submit-btn" size="large">
          <el-icon v-if="!loading"><Check /></el-icon>
          {{ loading ? '保存中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  User,
  UserFilled,
  Avatar,
  Message,
  Setting,
  Lock,
  Close,
  Check
} from '@element-plus/icons-vue'

interface Department {
  id: number
  name: string
  parentId?: number
  type: 'company' | 'department'
  userCount: number
  children?: Department[]
}

interface User {
  id?: number
  username: string
  nickname: string
  email: string
  role: 'admin' | 'staff' | 'user'
  status: 'active' | 'inactive'
  password?: string
  departmentId: number
}

interface Props {
  visible: boolean
  title: string
  formData: Partial<User>
  departments: Department[]
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: Partial<User>): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 本地表单数据
const localFormData = reactive<Partial<User>>({
  username: '',
  nickname: '',
  email: '',
  role: 'user',
  status: 'active',
  password: '',
  departmentId: 1
})

// 树形选择器配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 部门选项
const departmentOptions = computed(() => {
  return props.departments || []
})

// 开关状态计算属性
const statusSwitchValue = computed({
  get: () => localFormData.status === 'active',
  set: (value: boolean) => {
    localFormData.status = value ? 'active' : 'inactive'
  }
})

// 处理状态变化
const handleStatusChange = (value: boolean) => {
  localFormData.status = value ? 'active' : 'inactive'
}

// 表单验证规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
/*   nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度在 2 到 10 个字符', trigger: 'blur' }
  ], */
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  departmentId: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ]
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  Object.assign(localFormData, {
    username: '',
    nickname: '',
    email: '',
    role: 'user',
    status: 'active',
    password: '',
    departmentId: 1,
    ...newData
  })
}, { immediate: true, deep: true })

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    emit('submit', { ...localFormData })
    loading.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单输入')
    loading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
  emit('update:visible', false)
}

// 处理关闭
const handleClose = () => {
  emit('cancel')
}
</script>

<style scoped>
/* 弹窗整体样式 */
.user-dialog :deep(.el-dialog) {
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  overflow: hidden;
}

.user-dialog :deep(.el-dialog__header) {
  padding: 0;
  border-bottom: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-dialog :deep(.el-dialog__body) {
  padding: 0;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
}

.user-dialog :deep(.el-dialog__footer) {
  padding: 0;
  border-top: none;
  background: #ffffff;
}

.user-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transition: all 0.3s ease;
}

.user-dialog :deep(.el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.user-dialog :deep(.el-dialog__close) {
  color: white;
  font-size: 18px;
}

/* 自定义头部样式 */
.dialog-header {
  display: flex;
  align-items: center;
  padding: 10px;
}

.header-icon {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  backdrop-filter: blur(10px);
}

.header-content {
  flex: 1;
}

.header-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-subtitle {
  font-size: 14px;
  margin: 0;
  opacity: 0.9;
  font-weight: 400;
}

/* 弹窗主体样式 */
.dialog-body {
  max-height: 60vh;
  overflow-y: auto;
}

.user-form {
  max-width: none;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 28px;
  background: white;
  border-radius: 16px;
  padding: 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border: 1px solid #f1f5f9;
  position: relative;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f1f5f9;
}

.section-title .el-icon {
  color: #667eea;
  font-size: 18px;
}

/* 表单网格布局 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  align-items: start;
}

.form-grid .el-form-item {
  margin-bottom: 0;
}

/* 单列表单项 */
.form-single {
  grid-column: 1 / -1;
}

/* 增强的表单项样式 */
.form-item-enhanced {
  margin-bottom: 24px;
}

.form-item-enhanced :deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.5;
}

.form-item-enhanced :deep(.el-input) {
  height: 44px;
}

.form-item-enhanced :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  padding: 0 16px;
  height: 44px;
}

.form-item-enhanced :deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-select .el-input__wrapper) {
  border-radius: 12px;
}

.form-item-enhanced :deep(.el-select) {
  width: 100%;
}

.form-item-enhanced :deep(.el-input__inner) {
  height: 42px;
  line-height: 42px;
}

/* 角色选项样式 */
.role-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 8px 0;
}

.role-desc {
  font-size: 12px;
  color: #64748b;
  margin-left: 8px;
}

/* 状态开关样式 */
.status-switch-container {
  display: flex;
  align-items: center;
}

.status-switch-container :deep(.el-switch) {
  --el-switch-on-color: #667eea;
  --el-switch-off-color: #ef4444;
}

.status-switch-container :deep(.el-switch__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.status-switch-container :deep(.el-switch__label.is-active) {
  color: #667eea;
}

.status-switch-container :deep(.el-switch__label:not(.is-active)) {
  color: #ef4444;
}

/* 底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 24px 30px 30px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
}

.cancel-btn {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  color: #64748b;
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.submit-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .dialog-header {
    padding: 20px;
  }

  .header-title {
    font-size: 20px;
  }

  .dialog-body {
    padding: 20px;
  }

  .form-section {
    padding: 20px;
    margin-bottom: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .status-switch-container {
    justify-content: flex-start;
  }

  .dialog-footer {
    padding: 20px;
    flex-direction: column;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

@media (max-width: 1024px) {
  .user-dialog :deep(.el-dialog) {
    width: 90% !important;
  }

  .form-grid {
    gap: 20px;
  }

  .status-switch-container {
    justify-content: flex-start;
  }
}

/* 滚动条样式 */
.dialog-body::-webkit-scrollbar {
  width: 6px;
}

.dialog-body::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.dialog-body::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 3px;
}

.dialog-body::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}
</style>
